const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
	_before: function() { // 通用预处理器

	},
	async QBPay(list = [], user_id, price, addr = {}) {
		// 在支付接口这里没有进行前端传递进来的数据验证
		let time = Date.now();
		price = parseInt(price)
		const transaction = await db.startTransaction()
		try {
			// Error单条数据修改只认Doc
			const userRes = await transaction.collection('uni-id-users').doc(user_id).get()
			if (userRes.data) {
				const updateUser = await transaction.collection('uni-id-users').doc(user_id).update({
					money: dbCmd.inc(-price)
				})
				// 1. 生成订单信息
				const updateRes = await transaction.collection('order').add({
					type: "goods",
					pay_type: "qb",
					total_fee: price,
					user_id: user_id,
					platform: "H5",
					status: 2,
					is_refund: false,
					refund_amount: 0,
					refund_count: 0,
					create_time: time,
					update_time: time,
					paid_time: time,
					info: "",
					address: addr, // Error
					goods_list: list,
					wait_status: 2
				});
				// console.error(updateRes)
				await transaction.commit()
				return {
					success: true,
					money: price,
				}
			} else {
				return {
					success: false,
					error: `rollback`,
					rollbackCode: -100,
				}
			}
		} catch (e) {
			await transaction.rollback()
			console.error(`transaction error`, e)

			return {
				success: false,
				error: e
			}
		}
	},
	async getOrderGoods() {
		let goodsRes2 = db.collection("order").where({
			wait_status: 2
		}).get()
		let goodsRes3 = db.collection("order").where({
			wait_status: 3
		}).get()
		let goodsRes4 = db.collection("order").where({
			wait_status: 4
		}).get()

		return {
			goods2: (await goodsRes2).data,
			goods3: (await goodsRes3).data,
			goods4: (await goodsRes4).data
		}
	},
	sure(_id) {
		return db.collection("order").doc(_id).update({
			wait_status: 4
		})
	},
	async commentOrderGoods(comment) {
		let addCommentNumber = await db.collection("goods").doc(comment.goods_id).update({
			comment_count: dbCmd.inc(1)
		})
		let res = await db.collection('order').doc(comment.order_id).update({
			['goods_list.' + comment.index]: {
				is_comment: true
			}
		})
		let addRes = await db.collection('comment').add({
			star: comment.star,
			content: comment.content,
			goods_id: comment.goods_id,
			user_id: comment.user_id,
			imgs: comment.imgs,
			create_time: Date.now()
		})
		// 把评论信息放到评论数据库中
		return res
	}
}
